#coding = utf-8
#双层的神经网络
import numpy as np
import tensorflow as tf
import matplotlib.pyplot as plt
from tensorflow.examples.tutorials.mnist import input_data

mnist = input_data.read_data_sets('MNIST_data/', one_hot=True)
#NETWORK TOPOLOGIES
n_hidden_1 = 256
n_hidden_2 = 128
n_input = 784
n_classes = 10
#INPUTS AND OUTPUTS
x = tf.placeholder("float", [None, 784])
y = tf.placeholder("float", [None, 10])
#NETWORK PARAMETERS
stddev = 0.1
weights = {
    'w1': tf.Variable(tf.random_normal([n_input, n_hidden_1], stddev = stddev)),
    'w2': tf.Variable(tf.random_normal([n_hidden_1, n_hidden_2], stddev = stddev)),
    'out': tf.Variable(tf.random_normal([n_hidden_2, n_classes], stddev = stddev))
}
bias = {
    'b1': tf.Variable(tf.random_normal([n_hidden_1])),
    'b2': tf.Variable(tf.random_normal([n_hidden_2])),
    'out': tf.Variable(tf.random_normal([n_classes]))
}
print("NETWORK READY")

def multilayer_perceptron(_X, _weights, _bias):
    layer_1 = tf.nn.sigmoid(tf.add(tf.matmul(_X, _weights['w1']), _bias['b1']))
    layer_2 = tf.nn.sigmoid(tf.add(tf.matmul(layer_1, _weights['w2']), _bias['b2']))
    return (tf.matmul(layer_2, _weights['out']) + _bias['out'])

#PREDICTION
pred = multilayer_perceptron(x, weights, bias)
#LOSS AND OPTIMZER
cost = tf.reduce_mean(tf.nn.sparse_softmax_cross_entropy_with_logits(labels=tf.argmax(y, 1), logits=pred))
optm = tf.train.GradientDescentOptimizer(learning_rate=0.001).minimize(cost)
corr = tf.equal(tf.arg_max(pred, 1), tf.arg_max(y, 1))
accr = tf.reduce_mean(tf.cast(corr, "float"))
#INITIALIZER
init = tf.global_variables_initializer()
print("FUNCTION READY")

#迭代次数
training_epochs = 100
#每次迭代选择的样本数
batch_size = 100
#展示
display_step = 4
sess = tf.Session()
sess.run(init)
for epoch in range(training_epochs):
    avg_cost = 0
    num_batch = int(mnist.train.num_examples/batch_size)
    for i in range(num_batch):
        batch_xs, batch_ys = mnist.train.next_batch(batch_size)
        sess.run(optm, feed_dict={x:batch_xs, y:batch_ys})
        feeds = {x:batch_xs, y:batch_ys}
        avg_cost += sess.run(cost, feed_dict=feeds)/num_batch
    #DISPLAY
    if epoch % display_step == 0:
        feeds_train = {x:batch_xs, y:batch_ys}
        feeds_test = {x:mnist.test.images, y:mnist.test.labels}
        train_acc = sess.run(accr, feed_dict=feeds_train)
        test_acc = sess.run(accr, feed_dict=feeds_test)
        print("Epoch: %03d/%03d cost: %.9f train_acc: %.3f test_acc: %.3f"%(epoch, training_epochs, avg_cost, train_acc, test_acc))
print('Done!')

